package com.gmadmin.sysadmin.security.service;

import cn.hutool.core.util.StrUtil;
import com.gmadmin.sysadmin.security.config.SecurityProperties;
import com.gmadmin.sysadmin.security.dto.OnlineUserDto;
import com.gmadmin.sysadmin.security.dto.UserDetailsDto;
import com.gmadmin.sysadmin.security.utils.HttpRequestUtils;
import com.gmadmin.sysadmin.security.utils.RedisUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@AllArgsConstructor
public class OnlineUserService {

    private final SecurityProperties properties;
    private final RedisUtils redisUtils;

    /**
     * 保存在线用户信息
     * @param loginKey loginKey
     * @param userDetailsDto 用户认证信息
     * @param token token
     * @param request HttpServletRequest
     */
    public void save(String loginKey, UserDetailsDto userDetailsDto, String token, HttpServletRequest request){
        String ip = HttpRequestUtils.getIp(request);
        Integer id = userDetailsDto.getUser().getId();
        String browser = HttpRequestUtils.getBrowser(request);
        String address = HttpRequestUtils.getCityInfo(ip);
        OnlineUserDto onlineUserDto = null;
        try {
            onlineUserDto = new OnlineUserDto(id, userDetailsDto.getUsername(), userDetailsDto.getUser().getNickName(), browser , ip,
                    address, token, LocalDateTime.now(), userDetailsDto);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        redisUtils.set(loginKey, onlineUserDto, properties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
    }

    /**
     * 查询全部数据，不分页
     * @param username 账号
     * @return List<OnlineUserDto>
     */
    public List<OnlineUserDto> getAll(String username){
        String loginKey = properties.getOnlineKey() +
                (StrUtil.isBlank(username) ? "" : "*" + username);
        List<String> keys = redisUtils.scan(loginKey + "*");
        Collections.reverse(keys);
        List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
        for (String key : keys) {
            onlineUserDtos.add(redisUtils.get(key, OnlineUserDto.class));
        }
        onlineUserDtos.sort((o1, o2) -> o2.loginTime().compareTo(o1.loginTime()));
        return onlineUserDtos;
    }

    /**
     * 退出登录
     * @param loginKey loginKey
     */
    public void logout(String loginKey) {
        redisUtils.del(loginKey);
    }

    /**
     * 查询用户
     * @param key key
     * @return OnlineUserDto
     */
    public OnlineUserDto getOne(String key) {
        return redisUtils.get(key, OnlineUserDto.class);
    }

    /**
     * 根据用户名强退用户
     * @param username 账号
     */
    public void kickOutForUsername(String username) {
        String loginKey = properties.getOnlineKey() + username + "*";
        redisUtils.scanDel(loginKey);
    }
}
